import React, { useState, useEffect } from 'react';
import {
  Modal,
  Tree,
  Button,
  Space,
  Toast,
  Typography,
  Spin,
  Empty,
  Divider,
  Tag,
} from '@douyinfe/semi-ui';
import { IconUser, IconUserGroup, IconMenu } from '@douyinfe/semi-icons';
import { menuApi } from '../api/menu';

const { Title, Text } = Typography;

interface MenuNode {
  key: string;
  label: string;
  value: string;
  children?: MenuNode[];
  menuType?: number; // 1-目录 2-菜单 3-按钮
  checked?: boolean;
  permission?: string;
}

interface MenuPermissionAssignmentProps {
  visible: boolean;
  onCancel: () => void;
  targetType: 'user' | 'role'; // 分配目标类型：用户或角色
  targetId?: number; // 目标ID
  targetName?: string; // 目标名称
  onSuccess?: () => void;
}

const MenuPermissionAssignment: React.FC<MenuPermissionAssignmentProps> = ({
  visible,
  onCancel,
  targetType,
  targetId,
  targetName,
  onSuccess,
}) => {
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [menuTree, setMenuTree] = useState<MenuNode[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [originalCheckedKeys, setOriginalCheckedKeys] = useState<string[]>([]);

  // 转换菜单数据为树节点格式
  const convertMenuToTreeNode = (menus: any[]): MenuNode[] => {
    return menus.map(menu => ({
      key: menu.id.toString(),
      label: menu.menuName,
      value: menu.id.toString(),
      menuType: menu.menuType,
      permission: menu.permission,
      children: menu.children ? convertMenuToTreeNode(menu.children) : undefined,
    }));
  };

  // 加载菜单树数据
  const loadMenuTree = async () => {
    if (!targetId) return;
    
    setLoading(true);
    try {
      // 获取所有菜单树
      const menuTreeData = await menuApi.getMenuTree();
      const treeNodes = convertMenuToTreeNode(menuTreeData);
      setMenuTree(treeNodes);
      
      // 获取已分配的菜单权限
      let response;
      if (targetType === 'user') {
        // 获取用户已分配的菜单权限
        response = await fetch(`/system/user/${targetId}/menus`);
      } else {
        // 获取角色已分配的菜单权限
        response = await fetch(`/system/user/role/${targetId}/menus`);
      }
      
      if (response.ok) {
        const result = await response.json();
        if (result.success && result.data) {
          const assignedMenuIds = result.data.map((menu: any) => menu.id.toString());
          setCheckedKeys(assignedMenuIds);
          setOriginalCheckedKeys([...assignedMenuIds]);
        }
      }
      
      // 默认展开所有节点
      const allKeys = extractAllKeys(treeNodes);
      setExpandedKeys(allKeys);
    } catch (error) {
      console.error('加载菜单树失败:', error);
      Toast.error('加载菜单数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 提取所有菜单键
  const extractAllKeys = (nodes: MenuNode[]): string[] => {
    const keys: string[] = [];
    const traverse = (nodeList: MenuNode[]) => {
      nodeList.forEach(node => {
        keys.push(node.key);
        if (node.children) {
          traverse(node.children);
        }
      });
    };
    traverse(nodes);
    return keys;
  };

  // 处理菜单选择变化
  const handleCheck = (checkedKeys: string[]) => {
    setCheckedKeys(checkedKeys);
  };

  // 保存菜单权限分配
  const handleSave = async () => {
    if (!targetId) return;
    
    setSubmitting(true);
    try {
      const menuIds = checkedKeys.map(key => parseInt(key));
      
      let response;
      if (targetType === 'user') {
        // 分配用户菜单权限
        response = await fetch('/system/user/assign-menus', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userId: targetId,
            menuIds,
          }),
        });
      } else {
        // 分配角色菜单权限
        response = await fetch('/system/user/role/assign-menus', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            roleId: targetId,
            menuIds,
          }),
        });
      }
      
      if (!response.ok) {
        throw new Error('保存菜单权限失败');
      }
      
      const result = await response.json();
      if (result.success) {
        Toast.success('菜单权限分配成功');
        onSuccess?.();
        onCancel();
      } else {
        throw new Error(result.message || '保存菜单权限失败');
      }
    } catch (error) {
      console.error('保存菜单权限失败:', error);
      Toast.error('保存菜单权限失败');
    } finally {
      setSubmitting(false);
    }
  };

  // 重置菜单选择
  const handleReset = () => {
    setCheckedKeys([...originalCheckedKeys]);
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    const allKeys = extractAllKeys(menuTree);
    if (checkedKeys.length === allKeys.length) {
      setCheckedKeys([]);
    } else {
      setCheckedKeys(allKeys);
    }
  };

  // 渲染菜单节点
  const renderTreeNode = (node: MenuNode) => {
    const getTypeTag = (type?: number) => {
      switch (type) {
        case 1:
          return <Tag color="blue" size="small">目录</Tag>;
        case 2:
          return <Tag color="green" size="small">菜单</Tag>;
        case 3:
          return <Tag color="orange" size="small">按钮</Tag>;
        default:
          return null;
      }
    };

    return (
      <div className="flex items-center justify-between w-full">
        <span className="flex items-center gap-2">
          {node.label}
          {getTypeTag(node.menuType)}
          {node.permission && (
            <Text type="tertiary" size="small" className="ml-2">
              {node.permission}
            </Text>
          )}
        </span>
      </div>
    );
  };

  // 监听弹窗显示状态
  useEffect(() => {
    if (visible && targetId) {
      loadMenuTree();
    } else {
      // 重置状态
      setMenuTree([]);
      setCheckedKeys([]);
      setExpandedKeys([]);
      setOriginalCheckedKeys([]);
    }
  }, [visible, targetId, targetType]);

  const hasChanges = JSON.stringify(checkedKeys.sort()) !== JSON.stringify(originalCheckedKeys.sort());

  return (
    <Modal
      title={
        <div className="flex items-center gap-2">
          {targetType === 'user' ? <IconUser /> : <IconUserGroup />}
          <span>
            为{targetType === 'user' ? '用户' : '角色'}「{targetName}」分配菜单权限
          </span>
        </div>
      }
      visible={visible}
      onCancel={onCancel}
      width={700}
      height={700}
      footer={
        <div className="flex justify-between items-center">
          <div className="flex items-center gap-2">
            <Button size="small" onClick={handleSelectAll}>
              {checkedKeys.length === extractAllKeys(menuTree).length ? '取消全选' : '全选'}
            </Button>
            <Button size="small" onClick={handleReset} disabled={!hasChanges}>
              重置
            </Button>
            <Text type="tertiary" size="small">
              已选择 {checkedKeys.length} 个菜单
            </Text>
          </div>
          <Space>
            <Button onClick={onCancel}>取消</Button>
            <Button 
              type="primary" 
              onClick={handleSave}
              loading={submitting}
              disabled={!hasChanges}
            >
              保存
            </Button>
          </Space>
        </div>
      }
    >
      <div className="h-full flex flex-col">
        {loading ? (
          <div className="flex-1 flex items-center justify-center">
            <Spin size="large" />
          </div>
        ) : menuTree.length === 0 ? (
          <div className="flex-1 flex items-center justify-center">
            <Empty 
              image={<IconMenu size="extra-large" />}
              title="暂无菜单数据"
              description="请先配置系统菜单"
            />
          </div>
        ) : (
          <div className="flex-1 overflow-auto">
            <div className="mb-4 p-3 bg-gray-50 rounded">
              <div className="flex items-center gap-2 mb-2">
                <IconMenu />
                <Text strong>菜单权限说明</Text>
              </div>
              <div className="text-sm text-gray-600 space-y-1">
                <div>• <Tag color="blue" size="small">目录</Tag> 菜单目录访问权限</div>
                <div>• <Tag color="green" size="small">菜单</Tag> 页面菜单访问权限</div>
                <div>• <Tag color="orange" size="small">按钮</Tag> 操作按钮权限</div>
              </div>
            </div>
            
            <Divider margin="12px" />
            
            <Tree
              treeData={menuTree}
              checkable
              multiple
              checkedKeys={checkedKeys}
              expandedKeys={expandedKeys}
              onCheck={handleCheck}
              onExpand={setExpandedKeys}
              renderFullLabel={renderTreeNode}
              checkRelation="related"
              defaultExpandAll
            />
          </div>
        )}
      </div>
    </Modal>
  );
};

export default MenuPermissionAssignment;